package com.heima.comment.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.comment.Mapper.CommentMapper;
import com.heima.comment.pojo.ApComment;
import com.heima.comment.pojo.ApCommentLike;
import com.heima.comment.service.CommentService;
import com.heima.feign.article.IArticleClient;
import com.heima.feign.user.IUserClient;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.article.pojos.ApArticleConfig;
import com.heima.model.comment.dto.CommentDto;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.pojos.ApUser;
import com.heima.model.wemedia.dtos.WmCommentDto;
import com.heima.utils.thread.AppThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;


/**
 * @projectName: leadnews-project
 * @package: com.heima.comment.service.impl
 * @className: CommentServiceImpl
 * @author: Eric
 * @description: TODO
 * @date: 2024/1/25 19:27
 * @version: 1.0
 */
@Service
@Slf4j
public class CommentServiceImpl implements CommentService {

    @Autowired
    private IArticleClient articleClient;
    @Autowired
    private IUserClient userClient;
    @Autowired
    private MongoTemplate mongoTemplate;
    @Override
    public ResponseResult<?> findByArticleId(CommentDto commentDto) {
        //1.检查参数
        if(commentDto==null || commentDto.getArticleId() == null ){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2.加载数据并按照时间降序
        Query query = Query.query(Criteria.where("entryId")
                .is(commentDto.getArticleId()))
                .with(PageRequest.of(0,5,Sort.by(Sort.Direction.DESC,"createdTime")));
        List<ApComment> list=mongoTemplate.find(query,ApComment.class);
        //3.判断是否登录
        ApUser user = AppThreadLocalUtil.getUser();
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        //查询当前评论中哪些数据被点赞
        List<String> idList=list.stream().map(ApComment::getId).collect(Collectors.toList());
        Query query1=Query.query(Criteria.where("commentId").in(idList).and("authorId").is(user.getId()));
        List<ApComment> apComments=mongoTemplate.find(query1,ApComment.class);
        if (apComments == null){
            return ResponseResult.okResult(list);
        }
        List<ApComment> resultList=new ArrayList<>();
        list.forEach(acList -> {
            ApComment apComment=new ApComment();
            BeanUtils.copyProperties(acList,apComment);
            for (ApComment apComment1:apComments){
                if (acList.getId().equals(apComment1.getCommentId())){
                    acList.setOperation((short)0);
                    break;
                }
            }
            resultList.add(acList);
        });
        return ResponseResult.okResult(resultList);
    }

    @Override
    public ResponseResult<?> like(CommentDto dto) {
        //1.检查参数
        if (dto == null || dto.getCommentId() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2.判断用户是否登录
        ApUser user = AppThreadLocalUtil.getUser();
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        ApComment apComment = mongoTemplate.findById(dto.getCommentId(), ApComment.class);
        //3.点赞：0点赞  1 取消点赞
        if (apComment !=null && dto.getOperation()==0){
            //更新评论点赞数量 点赞数量加1
            apComment.setLikes(apComment.getLikes()+1);
            mongoTemplate.save(apComment);

            //保存评论点赞数据
            ApCommentLike apCommentLike=new ApCommentLike();
            apCommentLike.setCommentId(apComment.getId());
            apCommentLike.setAuthorId(user.getId());
            mongoTemplate.save(apCommentLike);
        }else if (dto.getOperation()==1){
            //更新点赞数量
            assert apComment != null;
            int tmp= apComment.getLikes()-1;
            tmp =tmp < 1 ? 0 : tmp;
            apComment.setLikes(tmp);
            mongoTemplate.save(apComment);
            //删除评论点赞
            Query query = Query.query(Criteria.where("commentId").is(apComment.getId()).and("authorId").is(user.getId()));
            mongoTemplate.remove(query, ApCommentLike.class);
        }
        //4.取消点赞
        Map<String,Object> result=new HashMap<>();
        result.put("likes",apComment.getLikes());
        return ResponseResult.okResult(result);
    }

    @Override
    public ResponseResult<?> saveComment(CommentDto dto) {
        //1.检查参数
        if (dto == null || StringUtils.isBlank(dto.getContent()) || dto.getArticleId() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //校验文章是否可以评论
        if (!checkParam(dto.getArticleId())){
            return ResponseResult.errorResult(AppHttpCodeEnum.ARTICLE_STATUS_ERROR);
        }
        //字数不超过50
        if (dto.getContent().length() >140) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, "评论内容不能超过140字");
        }
        //2.判断是否登录
        ApUser user = AppThreadLocalUtil.getUser();
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        //获取到评论人员
        ApUser dbUser = userClient.findUserById(user.getId());
        if (dbUser == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, "当前登录信息有误");
        }
        ApComment apComment =new ApComment();
        apComment.setAuthorId(user.getId());
        apComment.setContent(dto.getContent());
        apComment.setCreatedTime(new Date());
        apComment.setEntryId(dto.getArticleId());
        apComment.setImage(dbUser.getImage());
        apComment.setAuthorName(dbUser.getName());
        apComment.setLikes(0);
        apComment.setReply(0);
        apComment.setType((short) 0);
        apComment.setFlag((short) 0);
        mongoTemplate.save(apComment);
        articleClient.addComment(dto.getArticleId());
        return ResponseResult.okResult(apComment);
    }

    /**
     * 检查一下我钱。
     *
     * @param articleId 文章ID.
     * @return boolean
     */
    private boolean checkParam(Long articleId) {
        //是否可以评论
        ResponseResult<?> configResult=articleClient.findArticleConfigByArticleId(articleId);
        if (!configResult.getCode().equals(200)||configResult.getData()==null){
            return false;
        }
        ApArticleConfig apArticleConfig= JSON.parseObject(JSON.toJSONString(configResult.getData()), ApArticleConfig.class);
        if (apArticleConfig==null|| !apArticleConfig.getIsComment()){
            return false;
        }
        return true;
    }
}
